//
//  MQComposePictureView.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/2/1.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

protocol HMComposePictureViewCellDelegate:NSObjectProtocol{
    func didClickDeleteButton(index:NSIndexPath)
}

private let MQComposePictureViewCellId = "MQComposePictureViewCellId"
private let itemMargin:CGFloat = 5

class MQComposePictureView: UICollectionView {
    var didClickPauseCell: (()->())?
    
    var images:[UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        self.hidden = true
        registerClass(MQComposePictureViewCell.self, forCellWithReuseIdentifier: MQComposePictureViewCellId)
        dataSource = self
        delegate = self
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
//        layout.itemSize = CGSizeMake((SCREENW - itemMargin * 2 - 16)/3, (SCREENW - itemMargin * 2 - 16)/3)
    }
    
    func addImage(image:UIImage){
        if images.count == 9 {
            SVProgressHUD.showErrorWithStatus("图片添加太多")
            return
        }
        self.hidden = false
        images.append(image)
        reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
       
        layout.itemSize = CGSizeMake((self.frame.width - itemMargin * 2)/3, ((self.frame.width - itemMargin * 2)/3))
    }
}

extension MQComposePictureView : UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (images.count == 0 || images.count == 9) ? images.count : (images.count + 1)
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MQComposePictureViewCellId, forIndexPath: indexPath) as! MQComposePictureViewCell
        if indexPath.item == images.count {
            cell.image = nil
        }else{
        
            cell.image = images[indexPath.item]
        }
        cell.indexPath = indexPath
        cell.delegate = self
//        cell.backgroundColor = RandomColor()
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == images.count{
            didClickPauseCell?()
        }
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
    }
}

extension MQComposePictureView:HMComposePictureViewCellDelegate{
    func didClickDeleteButton(index:NSIndexPath){
        images.removeAtIndex(index.item)
        reloadData()
        if images.count == 0{
            self.hidden = true
        }
    }
}


class MQComposePictureViewCell:UICollectionViewCell{
    
    weak var delegate:HMComposePictureViewCellDelegate?
    var indexPath:NSIndexPath?
    var image:UIImage?{
        didSet{
            if image == nil{
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named:"compose_pic_add_highlighted")
                deleteBtn.hidden = true
            }else{
                deleteBtn.hidden = false
                imageView.highlightedImage = nil
                imageView.image = image
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
//        printfLog(indexPath)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
        contentView.addSubview(imageView)
        contentView.addSubview(deleteBtn)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.contentView)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.contentView.snp_top)
            make.trailing.equalTo(self.contentView.snp_trailing)
        }
    }
    
    @objc private func didClickDeleteBtn(){
        printfLog(indexPath)
        delegate?.didClickDeleteButton(indexPath!)
    }
    
    private lazy var imageView:UIImageView = UIImageView()
    private lazy var deleteBtn:UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: "didClickDeleteBtn", forControlEvents: UIControlEvents.TouchUpInside)
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        return btn
    }()
    
    
}